package com.sagereal.wtc.factorymode.Activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.R;

public class BatteryActivity extends BaseActivity {
    private BroadcastReceiver mBatteryReceiver;
    private TextView mChargeStatus,mCurrentCharge,mCurrentVoltage,mCurrentTemperature;
    private Button mTestPass,mTestFail;
    private boolean mHasBeenCharging = false,mHasBeenNotCharging = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_battery);
        setTitle(getString(R.string.title_battery_test));
        // 初始化视图
        mChargeStatus = findViewById(R.id.charge_status);
        mCurrentCharge = findViewById(R.id.current_charge);
        mCurrentVoltage = findViewById(R.id.current_voltage);
        mCurrentTemperature = findViewById(R.id.current_temperature);
        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        // 注册广播接收器
        this.registerReceiver(this.broadcastReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        // 设置测试通过按钮的点击事件
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        unregisterReceiver(this.broadcastReceiver);
    }

    final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            mCurrentCharge.setText(String.format("%d", level) + getString(R.string.percent)); // 格式化电量为百分比
            // 获取电池状态
            int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean ischarging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
            boolean isnotcharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING || status == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
            // 更新充电状态
            mChargeStatus.setText(ischarging ? getString(R.string.charing) : getString(R.string.uncharge));
            // 获取电压和温度（如果可用）
            int voltage = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, -1);
            int temperature = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, -1);
            // 注意：电压通常以微伏为单位，温度通常以摄氏度为单位
            mCurrentVoltage.setText(String.format("%.0f", voltage / 1.0f) + getString(R.string.mV)); // 假设电压以微伏为单位
            mCurrentTemperature.setText(String.format("%.1f", (float) temperature / 10) + getString(R.string.temperature)); // 假设温度以十分之一摄氏度为单位
            // 更新充电状态标志
            if (ischarging) {
                mHasBeenCharging = true;
            }
            if (isnotcharging) {
                mHasBeenNotCharging = true;
            }
        }
    };

    private void initView() {
        // 初始化并注册广播接收器
        mBatteryReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
                boolean ischarging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                        status == BatteryManager.BATTERY_STATUS_FULL;
                boolean isnotcharging = status == BatteryManager.BATTERY_STATUS_DISCHARGING ||
                        status == BatteryManager.BATTERY_STATUS_NOT_CHARGING;
                if (ischarging) {
                    mHasBeenCharging = true;
                }
                if (isnotcharging) {
                    mHasBeenNotCharging = true;
                }
            }
        };
        // 注册广播接收器以监听充电状态变化
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(mBatteryReceiver, filter);
        //测试通过
        mTestPass.setOnClickListener(v -> {
            if (mHasBeenCharging && mHasBeenNotCharging) {
                // 发送包含电池项目ID和测试结果的Intent到ItemActivity
                Intent intent = new Intent(BatteryActivity.this, ItemTestActivity.class);
                intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
                intent.putExtra("status", "pass");
                intent.putExtra("check", getIntent().getStringExtra("check"));
                setResult(RESULT_OK , intent);
                finish();
            } else {
                // 弹出提示
                mTestPass.setEnabled(false);
                Toast.makeText(BatteryActivity.this, getString(R.string.battery_notify), Toast.LENGTH_SHORT).show();
                new Thread(() -> {
                    try {
                        Thread.sleep(3000); // 等待Toast显示时间
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 重新启用按钮
                    runOnUiThread(() -> mTestPass.setEnabled(true));
                }).start();
            }
        });
        //测试失败
        mTestFail.setOnClickListener(v -> {
            // 类似地发送Intent，但状态为"fail"
            Intent intent = new Intent(BatteryActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
    }
}
